"""
作者：Huayu Zong
日期：2022年04月15日
"""
from app import App
from aliyun_operation import Aliyun
import json
from queue import Queue
import threading
import urllib.request
import urllib.error
import time

#连接阿里云
PRODUCTKEY=None #你的产品key
DEVICENAME=None   #你的设备名称
DEVICESECRET=None#你的设备密码

send_data_queue = Queue()
receive_date_queue = Queue()
g_aliyun_client = None



#读取设备证书
def readDeviceCertificate():
    # 连接阿里云
    global PRODUCTKEY
    global DEVICENAME
    global DEVICESECRET

    with open(file='设备证书.txt', mode='r+', encoding='utf-8') as file:
        file_text = file.read()
        dataDict = json.loads(file_text)

        PRODUCTKEY = dataDict['ProductKey']
        DEVICENAME = dataDict['DeviceName']
        DEVICESECRET =  dataDict['DeviceSecret']
    pass

# 阿里云运行的线程
def AliyunOperation_thread(recv_queue, send_queue):
    global g_aliyun_client
    while True:
        if g_aliyun_client is None:
            # 创建一个Aliyun client
            readDeviceCertificate()
            g_aliyun_client = Aliyun(PRODUCTKEY, DEVICENAME, DEVICESECRET, recv_queue, send_queue)
        else:
            if check_internet_is_connect() is True:
                # todo 网络已经连接，并且阿里云未连接,则连接阿里云
                if g_aliyun_client.is_connected_aliyun is False:
                    g_aliyun_client.automatic_operation()
                else:  # todo 阿里云已连接
                    # 2. 从发送queue中读取数据
                    if not send_queue.empty():
                        dict_data = send_queue.get()
                        print('AliyunOperation-->send_data_queue:', dict_data)
                        g_aliyun_client.publish_topic(dict_data)
                        print(dict_data)
            else:
                g_aliyun_client.is_connected_aliyun = False
                print('Internet is disconnected！！！')
                recv_queue.put('Internet is disconnected！！！')

        recv_queue.put({'client_connect_aliyun_status': g_aliyun_client.is_connected_aliyun})
        g_aliyun_client.timeout_clear_ota_can_status(10)
        time.sleep(1)

# 检测网络状态
def check_internet_is_connect():
    try:
        res = urllib.request.urlopen('https://www.baidu.com')
        #print(res.status)
        return True
    except urllib.error.URLError as err:
        #print(err)
        return False


if __name__ == '__main__':
    # 创建并启动阿里云相关操作的线程
    aliyun_operation_thread = threading.Thread(target=AliyunOperation_thread, args=(receive_date_queue, send_data_queue))
    aliyun_operation_thread.daemon = True  # 保证进程结束，线程跟着一起结束
    aliyun_operation_thread.start()


    #等待阿里云客户端创建成功
    # while g_aliyun_client is None:
    #     pass


    # 创建App
    app = App(receive_date_queue, send_data_queue)
    app.main_window_loop()
    pass


'''
生成EXE方法：https://zhuanlan.zhihu.com/p/401581689

2.pyinstaller -F -w main.py：生成的exe没有黑色提示框
'''